import { ref, onMounted, onUnmounted } from 'vue'

// 替代 useWindowSize
export function useWindowSize() {
  const width = ref(window.innerWidth)
  const height = ref(window.innerHeight)

  const update = () => {
    width.value = window.innerWidth
    height.value = window.innerHeight
  }

  onMounted(() => {
    window.addEventListener('resize', update)
  })

  onUnmounted(() => {
    window.removeEventListener('resize', update)
  })

  return { width, height }
}

// 替代 useIntersectionObserver
export function useIntersectionObserver(target, callback, options = {}) {
  let observer = null

  onMounted(() => {
    observer = new IntersectionObserver((entries) => {
      callback(entries[0])
    }, options)

    if (target.value) {
      observer.observe(target.value)
    }
  })

  onUnmounted(() => {
    if (observer) {
      observer.disconnect()
    }
  })

  return {
    stop: () => {
      if (observer) {
        observer.disconnect()
      }
    }
  }
}

// 替代 useScroll
export function useScroll() {
  const x = ref(0)
  const y = ref(0)

  const update = () => {
    x.value = window.pageXOffset
    y.value = window.pageYOffset
  }

  onMounted(() => {
    window.addEventListener('scroll', update)
    update()
  })

  onUnmounted(() => {
    window.removeEventListener('scroll', update)
  })

  return { x, y }
}

// 替代 useLocalStorage
export function useLocalStorage(key, defaultValue) {
  const data = ref(defaultValue)

  const read = () => {
    try {
      const value = uni.getStorageSync(key)
      if (value) {
        data.value = JSON.parse(value)
      }
    } catch (e) {
      console.error('Error reading from storage:', e)
    }
  }

  const write = () => {
    try {
      uni.setStorageSync(key, JSON.stringify(data.value))
    } catch (e) {
      console.error('Error writing to storage:', e)
    }
  }

  read()
  watch(data, write, { deep: true })

  return data
} 